<%
	require 'controller/page_helper'
	require 'controller/question_helper'
	require 'controller/selection_helper'
	require 'model/question'
	require 'model/setting'

	#TODO 直接#find()を呼んでいる箇所をHelperメソッドに置き換え

	pageHelper = PageHelper.new

	questionHelper = QuestionHelper.new
	selectionHelper = SelectionHelper.new

	question = Question.new
	question.title = pageHelper.get_parameter("question_title")
	question.content = pageHelper.get_parameter("question_content")

	QuestionHelper.add(question)

	selectionSize = pageHelper.get_parameter("selection_size").to_i

	selectionContents = pageHelper.get_parameters("selection_text")
	correctNumbers = pageHelper.get_parameters("is_correct")
	
	#まだ決め打ち
	isCorrects = Array.new(selectionSize, "false")
	correctNumbers.each { |correctNumber|
		correctIndex = correctNumber.to_i
		isCorrects[correctIndex] = "correct"
	}	

	#今のところ決め打ち
	selectionSize.times { |i|
		#選択肢が未入力の場合は登録を飛ばす
		if (selectionContents[i] == "")
			next
		end

		#選択肢を登録する
		setting = Settings.new
	
		setting.question = question
		#選択肢の内容で検索(登録されていない場合はその場で登録)
		setting.selection = selectionHelper.searchSelectionByContetnt(selectionContents[i])
		setting.is_correct = isCorrects[i] == "correct" ? true : false;

		#TODO メソッド切り出し
		setting.save
	}

	#一覧の取得(暫定的に全て取得)
	questions = questionHelper.list()
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Edit question</title>
	</head>
	<body>
		<div id="container">

			<div id="header">
				<h2>問題リスト</h2>	
			</div>
			
			<div id="center-panel">
				<div id="question-list">
					<% if questions != nil 
								questions.each_with_index { |q, i| %>
						<div class="questions">
							<p><span>id：<%= q.id%></span><span style="margin-left:10px;">内容：<%= q.title%></span></p>
							<p><span>問題文：<%= q.content%></span></p>
							<% 
								Settings.find(:all, :conditions => "question_id = #{q.id}").each_with_index { |s, si| %>
							<% selection = Selection.find(s.selection_id)%>
							<% settings = Settings.find(:first, :conditions => "question_id = '#{q.id}' and selection_id = '#{selection.id}'")%>
							<p><span>選択肢<%= si+1%>：<%= selection.content%></span><span><%= settings.is_correct ? "←正解" : ""%></span></p>	
							<%	}
							%>
						</div>
					<%}
					   end %>
				</div>
			</div>
			
			<div id="footer">
			</div>
					
		</div>
	</body>
</html>